<?php
/**
 * 扩展后台管理页面
 * @author 楚羽幽 <Name_Cyu@Foxmail.com>
 */
namespace Admin\Controller;
class PlugsController extends AuthController
{
    private $db;
    /**
     * [_initialize 构造函数]
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();

        //删除插件缓存
        S('hooks',null);

        $this->db = D('Plugs');
        $this->assign('field',array('install'=> '已安装插件', 'plugs' => $this->db->getAdminList()));
    }



    /**
     * [index 插件列表]
     * @return [type] [description]
     */
    public function index()
    {
        $data = $this->db->getAddonList();
        $this->assign('data', $data);
        $this->display();
    }


    /**
     * [create 创建插件]
     * @return [type] [description]
     */
    public function create()
    {
        if (IS_POST)
        {
            if($this->db->create())
            {
                $data = $_POST;
                $data['has_adminlist'] = isset($_POST['has_adminlist']) ? 1 : 0; // 是否后台
                $data['has_outurl'] = isset($_POST['has_outurl']) ? 1 : 0; // 外部访问
                $data['config'] = isset($_POST['config']) ? 1 : 0; // 是否有配置文件

                // 插件名首字母大小
                $data['name'] = ucfirst($data['name']);

                // 验证安装目录权限
                if (!is_writable(UNION_ADDON_PATH))
                {
                    $this->error(UNION_ADDON_PATH . ' 不可写');
                }

                //-------------------插件目录----------------------
                $addonDir = UNION_ADDON_PATH . $data['name'] . '/';
                if(!\Lib\Util\Dir::create($addonDir))
                {
                    $this->error('插件目录创建失败');
                }

                //-------------------配置文件----------------------
                if ($data['config'])
                {
                    copy(MODULE_PATH . 'Data/Addon/configAddon.php', $addonDir . 'config.php');
                }

                //--------------------控制器目录----------------------
                if ($data['has_adminlist'] || $data['has_outurl'])
                {
                    if(!\Lib\Util\Dir::create($addonDir . 'Controller'))
                    {
                        $this->error('控制器目录创建失败');
                    }
                }

                //-------------------模型目录----------------------
                if($data['has_outurl'])
                {
                    $files[]    =   UNION_ADDON_PATH . "{$data['name']}/Model/";
                    $files[]    =   UNION_ADDON_PATH . "{$data['name']}/Model/{$data['name']}Model.class.php";
                }

                // 调用函数创建文件
                if(create_dir_or_files($files))
                {
                    $this->error('模型目录创建失败');
                }

                //--------------------模型数据初始写入----------------------
                if ($data['has_outurl'])
                {
                    $Model = <<<str
<?php
/**
 * 插件模型管理
 * {$data['title']} 插件
 * @author {$data['author']} <{$data['email']}>
 */
namespace Addons\\{$data['name']}\Model;
use Think\Model;
class {$data['name']}Model extends Model{
    // 模型内容开始
}
str;
                file_put_contents($addonDir . "Model/{$data['name']}Model.class.php", $Model);
                }

                //--------------------后台控制器----------------------
                if ($data['has_adminlist'])
                {
                    $controller = <<<str
<?php
/**
 * 后台插件管理控制器
 * {$data['title']} 插件
 * @author {$data['author']} <{$data['email']}>
 */
namespace Addons\\{$data['name']}\Controller;
use Admin\Controller\AddonsController;
class AdminController extends AddonController{

    public function index() {
        \$this->display();
    }
}
str;
            file_put_contents($addonDir . 'Controller/AdminController.class.php', $controller);
        }

        //--------------------前台控制器----------------------
        if ($data['has_outurl'])
        {
            $controller = <<<str
<?php
/**
 * 前台控制器
 * {$data['title']} 插件
 * @author {$data['author']} <{$data['email']}>
 */
namespace Addons\\{$data['name']}\Controller;
use Home\Controller\AddonsController;
class IndexController extends AddonController{

    public function index() {
        \$this->display();
    }
}
str;
            file_put_contents($addonDir . 'Controller/IndexController.class.php', $controller);
        }


        //--------------------插件控制器----------------------
        $addonData = <<<str
<?php
/**
 * {$data['title']} 插件
 * @author {$data['author']} <{$data['email']}>
 */
namespace Addons\\{$data['name']};
use Common\Controller\Addon;
class {$data['name']}Addon extends Addon
{

    // 插件信息
    public \$info = array(
        'name' => '{$data['name']}',
        'title' => '{$data['title']}',
        'description' => '{$data['description']}',
        'status' => 1,
        'author' => '{$data['author']}',
        'email' => '{$data['email']}',
        'version' => '{$data['version']}',
        'has_adminlist' => {$data['has_adminlist']},
    );

    // 安装
    public function install()
    {
        return true;
    }

    // 卸载
    public function uninstall()
    {
        return true;
    }
str;
            if (isset($data['hooks']))
            {
                foreach ($data['hooks'] as $hook)
                {
                    $addonData .= "
    // 实现的{$hook}钩子方法
    public function {$hook}(\$param){
    }\n";
                }
            }
            $addonData .= "\n" . '}';
            file_put_contents($addonDir . $data['name'] . 'Addon.class.php', $addonData);
            // 创建View视图文件
            if ($data['has_adminlist'])
            {
                \Lib\Util\Dir::create($addonDir . 'View/Admin');
                copy(MODULE_PATH . 'Data/Addon/addonAdmin.php', $addonDir . 'View/Admin/index.php');
            }
            if ($data['has_outurl'])
            {
                \Lib\Util\Dir::create($addonDir . 'View/Index');
                copy(MODULE_PATH . 'Data/Addon/addonIndex.html', $addonDir . 'View/Index/index.html');
            }
            $this->success('插件创建成功！', U('index'));
            }
            else
            {
                $this->error($this->db->getError());
            }         
        }
        else
        {
            $this->assign('Hooks', M('Hooks')->select());
            $this->display();
        }
    }

    /**
     * [install 安装插件]
     * @return [type] [description]
     */
    public function install()
    {
        if ($this->db->installAddon())
        {
            $this->success('安装成功，请刷新后台');
        }
        else
        {
            $this->error($this->db->error);
        }
    }

    /**
     * [uninstall 卸载插件]
     * @return [type] [description]
     */
    public function uninstall()
    {
        if ($this->db->uninstallAddon()) {
            $this->success('卸载成功，请刷新后台');
        } else {
            $this->error($this->db->error);
        }
    }


    /*----------------------------------------属性定义----------------------------------------------*/

    /**
     * [help 查看帮助]
     * @return [type] [description]
     */
    public function help(){
        C('TPL_FIX','.html');
        $addon = I('addon');
        $this->display(UNION_ADDON_PATH . $addon . '/help');
    }
}
